package com.sc.contact.create;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;


public class DatFormat {

	private Map<String,Map<String,String>> groups = new HashMap<String,Map<String,String>>();
	private DefaultHttpClient client;

	public DatFormat(String user, String password) {
		client = new DefaultHttpClient();
		Credentials creds = new UsernamePasswordCredentials(user,password);
		client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
	}

	public void generate(PrintWriter pw, String parentName) {
		pw.println("Version=3.1.3");
		pw.println("G "+parentName+" "+parentName+" O");
		Iterator<String> groupsNames = groups.keySet().iterator();
		while (groupsNames.hasNext()) {
			String groupName = groupsNames.next();
			System.out.println("Generating group "+groupName);
			pw.println("G "+parentName+"::"+groupName.replaceAll(" ", ";")+" "+parentName+"::"+groupName.replaceAll(" ", ";")+" C");
			Map<String,String> group = groups.get(groupName);
			Iterator<String> entryNames = group.keySet().iterator();
			while (entryNames.hasNext()) {
				String entryName = entryNames.next();
				pw.println(group.get(entryName));
			}
		}
		pw.flush();
		pw.close();
	}

	public void addEntry(String groupName, String email) {
		// create group if it doesn't exist yet
		if (!groups.containsKey(groupName)) {
			groups.put(groupName,new HashMap<String,String>());
		}
		Map<String,String> group = groups.get(groupName);
		try {
			Entry entry = getEntry(email);
			group.put(groupName+email, "U "+entry.getId()+":: "+entry.getDisplayName().replaceAll(" ", ";")+",");
		}
		catch (Throwable t) {
			t.printStackTrace();
		}
	}

	public Entry getEntry(String email) throws ClientProtocolException, IOException {
		HttpGet httpget = new HttpGet("https://apps.na.collabserv.com/connections/opensocial/basic/rest/people/"+URLEncoder.encode(email,"UTF-8"));
		HttpResponse response = client.execute(httpget);
		String responseStr = IOUtils.toString(response.getEntity().getContent());
		Entry entry = new Entry(responseStr);
		return entry;

	}

}
